<?php
/*
set_time_limit(0);

require_once 'functions.php';
$file = dirname(__FILE__).DIRECTORY_SEPARATOR."cartoon.mp4  ";
$cmd = "ffmpeg -i http://eto.iobb.net:8003/cgi-bin/encoder?USER=admin&PWD=123456&GET_STREAM -vcodec copy -acodec copy -f mp4 -t 5 -y  ".$file." 2>&1";
$cmd = "ffmpeg -i 1.mp4 -vcodec copy -acodec copy -f mp4 -t 5 -y  ".$file." 2>&1";
$cmd = "ffmpeg -f mjpeg -i 'http://eto.iobb.net:8003/cgi-bin/encoder?USER=admin&PWD=123456&GET_STREAM'  -vcodec libx264 -vpre slow -b 500k -r 29.97 -t 5  ".$file ." 2>&1";
//shell_exec($cmd);
//exec($cmd,$out);
//2>&1
//$cmd = "ffmpeg -formats 2>&1";
exec($cmd,$output);
echo $cmd;
echo "<pre>";var_dump($output);
die('12');
//$argv[1] = "CM-2-8005";
*/
//$argv[1] = 3;
set_time_limit(0);
date_default_timezone_set('Asia/Tokyo');
if (isset($argv[1])) {
    require_once 'db/Db.class.php';
    require_once 'functions.php';
    $code = $argv[1];
    $db = new Db();
    //get camera
    $camera = $db->row('SELECT * FROM cameras as Camera WHERE Id = :Id', array('Id' => $code));
    if($camera){
        $folder = getFolderName($camera['CamID']);
        $time = $camera['duration'] * 3600;
        $flat = true;
        $number = getNextFile($code,$db);
        while ($flat) {
            $startDate = date('YmdHi');
            $fileMp4 = $startDate . ".mp4";
            $file = PATH_ROOT . 'video' . DIRECTORY_SEPARATOR . $folder . DIRECTORY_SEPARATOR . $fileMp4;
            $url = 'http://' . $camera['UniIp'] . ':' . $camera['HttpPort'] . '/cgi-bin/encoder?USER=' . $camera['UserName'] . '&PWD=' . $camera['Password'] . '&GET_STREAM';
            $cmd = 'ffmpeg -f mjpeg -i "' . $url . '" -vcodec libx264 -vpre slow -b 500k -r 29.97   -t ' . $time . ' "' . $file . '"';
            shell_exec($cmd);
            //save record
            $fileName = preg_replace('/[^A-Za-z0-9\-]/', '',$camera['CamName'])."_".$startDate."_".date('YmdHi');
            $data = array(
                'RecName' => $fileName,
                'RecPath' => $folder . '/' . $fileMp4,
                'CamId' => $code,
                'CrtDt' => date('Y-m-d H:i:s'),
                'UptDt' => date('Y-m-d H:i:s'),
            );
            $insert   =  $db->query("INSERT INTO records(RecName,RecPath,CamId,CrtDt,UptDt) VALUES(:RecName,:RecPath,:CamId,:CrtDt,:UptDt)", $data);
            //new file
            $camera = $db->row('SELECT * FROM cameras as Camera WHERE Id = :Id', array('Id' => $code));
            if ($camera && isset($camera['duration']) && $camera['is_start'] != 0) {
                $time = $camera['duration'] * 3600;
            } else {
                $flat = false;
            }
            $number++;
        }
    }
    die('12');
}
